import 'dart:ui';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';

import '../base/UrlPath.dart';
import '../base/javascript_channel.dart';
import '../shared_webview/ts_mine_home_page.dart';
import '../test_web_controller_util.dart';

/// Mix-in [DiagnosticableTreeMixin] to have access to [debugFillProperties] for the devtool
// ignore: prefer_mixin
class TSSharedWebViewContainerModel
    with ChangeNotifier, DiagnosticableTreeMixin {
  int _count = 0;
  int get count => _count;

  String _Url = UrlPath.gameUrl;
  String get Url => _Url;

  WebViewController? _webController;
  WebViewController get webController {
    if (_webController == null) {
      _webController = _defaultController;
      _loadRequest();
    }
    return _webController!;
  }

  _loadRequest() {
    webController.loadRequest(Uri.parse(Url));
  }

  BuildContext? _jsContext;

  void addCount() {
    _count++;
    notifyListeners();
  }

  /// Makes `Counter` readable inside the devtools by listing all of its properties
  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(IntProperty('count', count));
  }

  bool _checkContinue() {
    // if (!mounted) {
    //   debugPrint("Error❌:mounted=$mounted");
    //   return false;
    // }
    if (_jsContext == null) {
      debugPrint("Error❌:_jsContext 不能为空");
      return false;
    }
    return true;
  }

  _addJs() {
    Set<JavascriptChannel> javascriptChannels = {
      /// 跳转到app指定页面_Name
      JavascriptChannel(
        name: "mpCallApp_closeMiniProgram",
        onMessageReceived: (JavaScriptMessage message) {
          if (!_checkContinue()) return;
          Navigator.popUntil(_jsContext!, (route) {
            // 在根页面时就禁止再次返回
            if (route.settings.name == "/" || route.settings.name == "/home") {
              return true;
            }
            return false;
          });
        },
      ),
      JavascriptChannel(
        name: "mpCallApp_hideMiniProgram",
        onMessageReceived: (JavaScriptMessage message) {
          if (!_checkContinue()) return;
          Navigator.pop(_jsContext!);
        },
      ),
      JavascriptChannel(
        name: "mpCallApp_openAppUserDetail1",
        onMessageReceived: (JavaScriptMessage message) {
          if (!_checkContinue()) return;
          Navigator.push(_jsContext!, MaterialPageRoute(
            builder: (context) {
              String userId = "1475332557208702976";
              return TSMineHomeViewController(userId: userId);
            },
          ));
        },
      ),
      JavascriptChannel(
        name: "mpCallApp_openAppUserDetail2",
        onMessageReceived: (JavaScriptMessage message) {
          if (!_checkContinue()) return;
          Navigator.push(_jsContext!, MaterialPageRoute(
            builder: (context) {
              String userId = "234054";
              return TSMineHomeViewController(userId: userId);
            },
          ));
        },
      ),
    };

    for (var channel in javascriptChannels) {
      ShareWebViewController.javaScriptChannelNames ??= [];
      ShareWebViewController.javaScriptChannelNames!
          .add(channel.name ?? "unkonw");

      webController.addJavaScriptChannel(
        channel.name ?? "unkonw",
        onMessageReceived: channel.onMessageReceived,
      );
    }
  }

  WebViewController get _defaultController {
    PlatformWebViewControllerCreationParams params;
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      params = WebKitWebViewControllerCreationParams(
        allowsInlineMediaPlayback: true,
        mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
      );
    } else {
      params = const PlatformWebViewControllerCreationParams();
    }

    return WebViewController.fromPlatformCreationParams(params)
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0xfff1f1f1))
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageStarted: (String url) {
            // if (mounted) {
            //   setState(() {
            //     _showLoading = true;
            //   });
            // }
          },
          onPageFinished: (String url) {
            // _webViewWidget.getTitle().then((title) {
            //   if (mounted) {
            //   setState(() {
            //     _title =  title;
            //   });
            // }
            // });
            // if (mounted) {
            //   setState(() {
            //     _showLoading = false;
            //   });
            // }
          },
          onProgress: (int progress) {
            // _progressValue = progress / 100;
            // ToastUtil.showMessage('$progress%');

            // if (mounted) setState(() {});
          },
          onWebResourceError: (WebResourceError error) async {
            // _webController.getTitle().then((title) {});
            // _onErrorInnerHTML();
            //webview页面加载失败log
          },
        ),
      );
  }
}
